﻿using Newtonsoft.Json.Linq;
using System.IO;
using System.Text;
using System.Web;

namespace Utility.Helper
{
    public class AjaxResult
    {
        /// <summary>
        /// 获取当前请求的数据包并解析为JSON TO OBJECT (JObject)
        /// </summary>
        /// <returns></returns>
        public static JObject GetPostData(HttpContext context)
        {
            var jsonStr = "";
            using (var steam = new StreamReader(context.Request.InputStream))
            {
                jsonStr = steam.ReadToEnd();
            }
            return JObject.Parse(jsonStr);
        }

        /// <summary>
        /// (JSON)返回成功
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static void Success(HttpContext context, object data = null)
        {
            Reson(context, 1, data, "成功");
        }

        /// <summary>
        /// (JSON)返回错误
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static void Erro(HttpContext context, object data = null)
        {
            Reson(context, 0, data, "异常");
        }

        /// <summary>
        /// (JSON)返回消息
        /// </summary>
        /// <param name="code"></param>
        /// <param name="data"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static void Reson(HttpContext context, int code, object data, string msg)
        {
            if (msg == null)
            {
                msg = "";
            }
            var jObject = new JObject();
            jObject["Type"] = code;
            jObject["Msg"] = msg;
            if (data != null)
            {
                jObject["Data"] = JToken.FromObject(data);
            }
            context.Response.HeaderEncoding = Encoding.UTF8;
            context.Response.ContentType = "application/json";
            context.Response.Write(jObject.ToString());
            context.Response.End();

            ///context.ApplicationInstance.CompleteRequest();
            //return  Content(, "", );
        }
    }
}